package org.chnxi.leetcode.problems.ques14;

/**
 * 最长公共前缀
 * 执行用时 :1 ms, 在所有 Java 提交中击败了78.53%的用户
 * 内存消耗 :37.7 MB, 在所有 Java 提交中击败了27.50%的用户
 */
public class Simple01 {

    public static void main(String[] args) {
        String[] arr1 = {"flower", "flow", "flight"};
        String result1 = longestCommonPrefix(arr1);
        System.out.println("result1="+result1);

        String[] arr2 = {"dog", "rececar", "car"};
        String result2 = longestCommonPrefix(arr2);
        System.out.println("result2="+result2);

        String[] arr3 = {"aa" , "a"};
        String result3 = longestCommonPrefix(arr3);
        System.out.println("result3="+result3);

    }

    public static String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();

        //安全性验证
        if(strs==null || strs.length<1){
            return sb.toString();
        }

        //以第一个字符串为基准进行对比
        for (int i=0; i<strs[0].length(); i++){
            for (int j=0; j<strs.length;j++){
                //如果在第j个字符串的长度不够，或者j字符串的第i位比对失败，直接返回之前一致的结果
                if(strs[j].length() < i+1 || strs[0].charAt(i) != strs[j].charAt(i)){
                    return sb.toString();
                }
            }
            sb.append(strs[0].charAt(i));
        }

        return sb.toString();
    }

}
